package com.changgou.interceptor;


import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 *      feign的拦截器
 */
@Component
public class FeignInterceptor implements RequestInterceptor {






    @Override
    public void apply(RequestTemplate requestTemplate) {

        //传递令牌

        //获取到一个请求上下文的对象
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();


        if (requestAttributes!=null ){

            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();

            if (request!=null){

                //就可以通过request对象获取到全部的请求头信息
                Enumeration<String> headerNames = request.getHeaderNames();

                while (headerNames.hasMoreElements()){

                    String headerName = headerNames.nextElement();

                    if ("authorization".equals(headerName)){

                        // Bearer jwt  令牌
                        String headerValue = request.getHeader(headerName);

                        //传递令牌
                        requestTemplate.header(headerName,headerValue);

                    }

                }
            }

        }

    }
}
